package com.example.simpleforum.dao;

import com.example.simpleforum.model.Forum;
import com.example.simpleforum.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ForumDao {
    
    /**
     * 创建新板块
     */
    public int createForum(Forum forum) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int forumId = -1;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO forum (name, description, creator_id) VALUES (?, ?, ?)";
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, forum.getName());
            pstmt.setString(2, forum.getDescription());
            pstmt.setInt(3, forum.getCreatorId());
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    forumId = rs.getInt(1);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return forumId;
    }
    
    /**
     * 根据ID获取板块
     */
    public Forum findById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Forum forum = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM forum WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                forum = new Forum();
                forum.setId(rs.getInt("id"));
                forum.setName(rs.getString("name"));
                forum.setDescription(rs.getString("description"));
                forum.setCreatorId(rs.getInt("creator_id"));
                forum.setCreateTime(rs.getTimestamp("create_time"));
                forum.setUpdateTime(rs.getTimestamp("update_time"));
                forum.setStatus(rs.getBoolean("status"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return forum;
    }
    
    /**
     * 获取所有板块
     */
    public List<Forum> findAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Forum> forums = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM forum WHERE status = 1 ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Forum forum = new Forum();
                forum.setId(rs.getInt("id"));
                forum.setName(rs.getString("name"));
                forum.setDescription(rs.getString("description"));
                forum.setCreatorId(rs.getInt("creator_id"));
                forum.setCreateTime(rs.getTimestamp("create_time"));
                forum.setUpdateTime(rs.getTimestamp("update_time"));
                forum.setStatus(rs.getBoolean("status"));
                forums.add(forum);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return forums;
    }
    
    /**
     * 检查板块名称是否已存在
     */
    public boolean isNameExists(String name) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean exists = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT 1 FROM forum WHERE name = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                exists = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return exists;
    }
    
    /**
     * 根据名称搜索板块
     */
    public List<Forum> searchByName(String keyword) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Forum> forums = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM forum WHERE name LIKE ? AND status = 1 ORDER BY name";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + keyword + "%");
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Forum forum = new Forum();
                forum.setId(rs.getInt("id"));
                forum.setName(rs.getString("name"));
                forum.setDescription(rs.getString("description"));
                forum.setCreatorId(rs.getInt("creator_id"));
                forum.setCreateTime(rs.getTimestamp("create_time"));
                forum.setUpdateTime(rs.getTimestamp("update_time"));
                forum.setStatus(rs.getBoolean("status"));
                forums.add(forum);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return forums;
    }
    
    /**
     * 主管理员删除板块
     * @param forumId 板块ID
     * @return 删除成功返回true，失败返回false
     */
    public boolean deleteForumByMainAdmin(int forumId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            // 使用逻辑删除，将状态设置为0
            String sql = "UPDATE forum SET status = 0 WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, forumId);
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
}